import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/bookquiz.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/widgets/BGExamWidget.dart';
import 'package:ichinesereader/models/book/BookQuiz.dart';
import 'package:ichinesereader/models/book/BookQuizAnswerDto.dart';
import 'package:ichinesereader/models/book/BookQuizResult.dart';
import 'package:ichinesereader/pages/common/bookSettings.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/buttons/debouncedMaterialButton.dart';
import '../../widgets/dialogs/completeBook.dart';
import '../../widgets/dialogs/miniBook.dart';

class BookQuizEditor extends StatefulWidget {
  BookQuizEditor(
      {Key? key,
      required this.bookId,
      required this.bookcode,
      this.bookTitle,
      this.assignmentId})
      : super(key: key);
  final String bookId;
  final String bookcode;
  final String? bookTitle;
  final String? assignmentId;

  @override
  State<BookQuizEditor> createState() => _BookQuizEditorState();
}

class _BookQuizEditorState extends State<BookQuizEditor> {
  final BookQuizController _bookQuizController = Get.put(BookQuizController());
  final box = Hive.box('appconfig');

  List<QuestionItem> questionItems = [];
  Map<String, bool>? gradedAnswers = {};
  Map<int, bool> answeredList = {};
  BookQuiz bookQuiz = BookQuiz();
  String _lang = 'Mandarin';
  String _language = 'Simplified';
  TextOptions _textOption = TextOptions.Simplified;
  AudioOptions _audioOption = AudioOptions.Mandarin;
  final _formKey = GlobalKey<FormBuilderState>();
  int _selectedIndex = 0;
  BookQuizAnswerDto dto = BookQuizAnswerDto();
  int questionNumbers = 0;
  var counters = <int>{};
  bool firstAttempt = false;
  ValueNotifier valueNotifier = ValueNotifier(false);

  _getAnswer(value) {
    setState(() {
      answeredList[_selectedIndex] = true;
      if (!counters.contains(_selectedIndex)) {
        counters.add(_selectedIndex);
      }
      //dto.answers?['${_selectedIndex + 1}'] = ['${value.toString()}'];
      //dto.simple = _textOption == TextOptions.Simplified;
      print(questionItems[_selectedIndex].answer![0]);
      if (questionItems[_selectedIndex].answer == null) {
        questionItems[_selectedIndex].answer = [];
        questionItems[_selectedIndex].answer?.add(value);
        dto.simple = _textOption == TextOptions.Simplified;
      } else {
        questionItems[_selectedIndex].answer![0] = value;
      }
      if (counters.length > 0 && valueNotifier.value == false) {
        if (firstAttempt == false) {
          dto.answers?['${_selectedIndex + 1}'] = ['${value.toString()}'];
          valueNotifier.value = true;

          //暂时先这样处理，基本不影响
          // //print(dto.answers?['${_selectedIndex + 1}']?[0].toString());
          // if (dto.answers?['${_selectedIndex + 1}']?[0].toString() !=
          //     value.toString()) {
          //   dto.answers?['${_selectedIndex + 1}'] = ['${value.toString()}'];
          //   valueNotifier.value = true;
          // }
        } else {
          dto.answers?['${_selectedIndex + 1}'] = ['${value.toString()}'];
          if (dto.answers!.isNotEmpty &&
              dto.answers!.length == questionItems.length)
            valueNotifier.value = true;
        }
      } else {
        dto.answers?['${_selectedIndex + 1}'] = ['${value.toString()}'];
      }
    });
  }

  _submitQuizAnswers() {
    var quizResult = BookQuizResult();
    if (widget.assignmentId != null && widget.assignmentId != '') {
      _bookQuizController
          .postAssignmentBookQuizAnswer(
              widget.bookId, widget.assignmentId.toString(), this.dto)
          .then((result) {
        quizResult = result;
        showQuizDialog(Get.context!, quizResult, firstAttempt);
      });
    } else {
      _bookQuizController
          .postBookQuizAnswer(widget.bookId, this.dto)
          .then((result) {
        quizResult = result;
        showQuizDialog(Get.context!, quizResult, firstAttempt);
      });
    }
  }

  @override
  void initState() {
    if (widget.assignmentId != null && widget.assignmentId != '') {
      _lang = box.get('UserAssiLang') ?? 'Mandarin';
      _language = box.get('UserAssiLanguage') ?? 'Simplified';
    } else {
      // to keep the same setting as individual book setting
      if (box.get('_text') != null) {
        _language = box.get('_text');
      } else {
        _lang = box.get('UserLang') ?? 'Mandarin';
      }
      if (box.get('_audio') != null) {
        _language = box.get('_text');
      } else {
        _language = box.get('UserLanguage') ?? 'Simplified';
      }
    }

    if (_language == 'Traditional') {
      _textOption = TextOptions.Traditional;
    }
    if (_lang == 'Cantonese') {
      _audioOption = AudioOptions.Cantonese;
    }
    if (widget.assignmentId != null && widget.assignmentId != '') {
      _bookQuizController
          .getAssignmentBookQuiz(widget.bookId, widget.assignmentId.toString())
          .then((quiz) {
        this.bookQuiz = quiz;
        if (quiz.firstAttempt == true) {
          setState(() {
            questionItems = _bookQuizController.fromBookQuizToQuestionItems(
                quiz, _textOption, _audioOption);
            questionNumbers = questionItems.length;
            firstAttempt = true;
          });
        } else {
          setState(() {
            if (quiz.currentMaxScore != null &&
                quiz.currentMaxScore?.simple == true) {
              _textOption = TextOptions.Simplified;
            } else {
              _textOption = TextOptions.Traditional;
            }
            questionItems = _bookQuizController.fromBookQuizToQuestionItems(
                quiz, _textOption, _audioOption);
            questionNumbers = questionItems.length;
            gradedAnswers = quiz.currentMaxScore!.gradedAnswers!;
          });
        }

        if (bookQuiz.firstAttempt != null && bookQuiz.firstAttempt == false) {
          dto.answers = bookQuiz.currentMaxScore?.submittedAnswers;
          dto.simple = bookQuiz.currentMaxScore?.simple;
        } else {
          dto.answers = Map<String, List<String>>();
          if (_language == 'Simplified' || _language == 'No Text') {
            dto.simple = true;
          } else {
            dto.simple = false;
          }
        }
      });
    } else {
      _bookQuizController
          .getBookQuiz(widget.bookId, _textOption, _audioOption)
          .then((quiz) {
        this.bookQuiz = quiz;
        if (quiz.firstAttempt == true) {
          setState(() {
            questionItems = _bookQuizController.fromBookQuizToQuestionItems(
                quiz, _textOption, _audioOption);
            questionNumbers = questionItems.length;
            firstAttempt = true;
          });
        } else {
          setState(() {
            if (quiz.currentMaxScore != null &&
                quiz.currentMaxScore?.simple == true) {
              _textOption = TextOptions.Simplified;
            } else {
              _textOption = TextOptions.Traditional;
            }

            questionItems = _bookQuizController.fromBookQuizToQuestionItems(
                quiz, _textOption, _audioOption);
            questionNumbers = questionItems.length;
            gradedAnswers = quiz.currentMaxScore!.gradedAnswers!;
          });
        }

        if (bookQuiz.firstAttempt != null && bookQuiz.firstAttempt == false) {
          dto.answers = bookQuiz.currentMaxScore?.submittedAnswers;
          dto.simple = bookQuiz.currentMaxScore?.simple;
        } else {
          dto.answers = Map<String, List<String>>();
          if (_language == 'Simplified' || _language == 'No Text') {
            dto.simple = true;
          } else {
            dto.simple = false;
          }
        }
      });
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build common book quiz editor${questionItems.length}');

    return Scaffold(
      appBar: AppBar(
        // leading: BackButton(onPressed: () {
        //   //_booksController.updateBookItemStatus(widget.readingType);
        // }),
        title: Container(
          width: double.infinity,
          height: 40,
          child: Center(
            child: Text(this.widget.bookTitle != null
                ? this.widget.bookTitle.toString()
                : ''),
          ),
        ),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        primary: false,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 15),
          child: Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  if (questionItems.isNotEmpty)
                    FormBuilder(
                      key: _formKey,
                      child: FormBuilderChoiceChip(
                        padding: const EdgeInsets.all(10),
                        initialValue: questionItems[_selectedIndex],
                        spacing: 10.0,
                        //runSpacing: 8,
                        alignment: WrapAlignment.start,
                        labelPadding: EdgeInsets.symmetric(
                          horizontal: 15.0,
                        ),
                        selectedColor: Get.isDarkMode
                            ? (Colors.white)
                            : Get.theme.primaryColorLight,
                        elevation: 1.0,
                        backgroundColor: Colors.transparent,
                        decoration: InputDecoration(
                          labelStyle: Get.theme.textTheme.labelSmall,
                          border: InputBorder.none,
                        ),
                        name: 'choice_chip',
                        onChanged: (value) {
                          if (value == null) return;
                          setState(() {
                            _selectedIndex =
                                questionItems.indexOf(value as QuestionItem);
                          });
                        },
                        options: questionItems
                            .map((item) => FormBuilderChipOption<QuestionItem>(
                                value: item,
                                child: Badge(
                                  backgroundColor: Colors.transparent,
                                  // badgeStyle: myBadges.BadgeStyle(
                                  //   badgeColor: Colors.transparent,
                                  //   borderRadius:
                                  //       BorderRadius.circular(5),
                                  //   padding: EdgeInsets.all(1),
                                  // ),
                                  // position:
                                  //     myBadges.BadgePosition.topEnd(
                                  //         top: -10, end: -25),

                                  isLabelVisible:
                                      bookQuiz.firstAttempt == false,
                                  label: gradedAnswers!.values.length >
                                              questionItems.indexOf(item) &&
                                          gradedAnswers!.values.toList()[
                                                  questionItems
                                                      .indexOf(item)] ==
                                              true
                                      ? Icon(
                                          Icons.check,
                                          color: Colors.green,
                                          size: 16,
                                        )
                                      : Icon(Icons.close,
                                          color: Colors.red, size: 16),
                                  child: Text(
                                    (questionItems.indexOf(item) + 1)
                                        .toString(),
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontFamily: 'Montserrat',
                                      fontWeight: FontWeight.w800,
                                      color: answeredList[questionItems
                                                  .indexOf(item)] ==
                                              true
                                          ? Color.fromARGB(255, 255, 123, 7)
                                          : Colors.black,
                                    ),
                                  ),
                                )
                                // : Text(
                                //     (questionItems.indexOf(item) + 1)
                                //         .toString(),
                                //     style: TextStyle(
                                //       fontSize: 16,
                                //       fontFamily: 'Montserrat',
                                //       fontWeight: FontWeight.w800,
                                //       color: answeredList[questionItems
                                //                   .indexOf(item)] ==
                                //               true
                                //           ? Color.fromARGB(
                                //               255, 255, 123, 7)
                                //           : Colors.black,
                                //     ),
                                //   ),
                                ))
                            .toList(),
                      ),
                    ),
                  if (questionItems.isNotEmpty)
                    GestureDetector(
                      onHorizontalDragEnd: (DragEndDetails details) {
                        // //// swipe to go back or forward
                        // if (details.primaryVelocity! > 0) {
                        //   if (_selectedIndex > 0) {
                        //     setState(() {
                        //       _selectedIndex--;
                        //       // print(_selectedIndex);
                        //     });
                        //   }
                        // } else if (details.primaryVelocity! < 0) {
                        //   // User swiped Right
                        //   if (_selectedIndex < questionItems.length - 1) {
                        //     setState(() {
                        //       _selectedIndex++;
                        //       // print(_selectedIndex);
                        //     });
                        //   }
                        // }
                      },
                      child: BGExamWidget(
                          questionItem: questionItems[_selectedIndex],
                          getAnswer: _getAnswer,
                          mode: BGExamWidgetMode.Practice),
                    ),
                  Container(
                    width: (MediaQuery.of(context).size.width) * 0.8,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        MaterialButton(
                            color: Theme.of(context).colorScheme.secondary,
                            onPressed: () {
                              if (_selectedIndex > 0) {
                                setState(() {
                                  _selectedIndex--;
                                  _formKey.currentState!.patchValue({
                                    'choice_chip': questionItems[_selectedIndex]
                                  });
                                });
                              }
                            },
                            child: Text('Prev'.tr)),
                        SizedBox(
                          width: 20,
                        ),
                        MaterialButton(
                            color: Theme.of(context).colorScheme.secondary,
                            onPressed: () {
                              if (_selectedIndex < questionItems.length - 1) {
                                setState(() {
                                  _selectedIndex++;
                                  _formKey.currentState!.patchValue({
                                    'choice_chip': questionItems[_selectedIndex]
                                  });
                                });
                              }
                            },
                            child: Text('Next'.tr)),
                        SizedBox(
                          width: 20,
                        ),
                        Visibility(
                          //visible: questionNumbers == counters.length,
                          visible: valueNotifier.value == true,
                          child: MaterialButton(
                              //debounceTimeMs: 800,
                              color: Theme.of(context).colorScheme.secondary,
                              onPressed: () {
                                _submitQuizAnswers();
                              },
                              child: Text('Submit'.tr)),
                        ),
                        SizedBox(
                          width: 20,
                        ),
                        DebouncedMaterialButton(
                            debounceTimeMs: 800,
                            color: Theme.of(context).colorScheme.secondary,
                            onPressed: () {
                              showDialog(
                                  context: context,
                                  builder: (BuildContext context) {
                                    return MiniBookDialog(
                                        btitle: widget.bookTitle!,
                                        bid: widget.bookId,
                                        bcode: widget.bookcode,
                                        lang: _lang,
                                        language: _language,
                                        assignmentId: widget.assignmentId);
                                  });
                            },
                            child: Icon(Icons.book,
                                color: Colors.amber, size: 21.0))
                      ],
                    ),
                  ),
                ]),
          ),
        ),
      ),
    );
  }

  void showQuizDialog(
      BuildContext context, BookQuizResult results, bool firstAttempt) async {
    await showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return CompleteBookDialog(
              btitle: widget.bookTitle!,
              bid: widget.bookId,
              results: results,
              firstAttempt: firstAttempt);
        });
  }
}
